//
//  SZLTabBarViewController.m
//  Shengzhuli
//
//  Created by 卡忙科技 on 16/7/18.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue &0xFF00) >>8))/255.0 blue:((float)(rgbValue &0xFF))/255.0 alpha:1.0]

#import "SZLTabBarViewController.h"
#import "ConNavigationontroller.h"
#import "ConHomeViewController.h"
#import "ConShoppingMallsController.h"
#import "ConInformationController.h"
#import "ConPersonalController.h"
#import "UserProfileManager.h"
#import "GGTabBar.h"
#import "SZLAccountHelper.h"
#import "PersonNetWork.h"
#import "WaterRippleWait.h"
#import "ShareTool.h"
#import "MBProgressHUD+MJ.h"
#import "AddCoverView.h"
#import "ConQrCodeScannerController.h"
#import "HomeNearAdderViewController.h"
#import "ConActivityDetailController.h"
#import "ConRecomendViewController.h"
#import "ConVipViewController.h"
#import "ConYueViewController.h"

#import "ConNewHomeVc.h"
#import "NewPersonalVc.h"
#import "ConYueVc.h"

@interface SZLTabBarViewController ()<AddCoverViewDelegate>

@property (strong, nonatomic) NSDate *lastPlaySoundDate;

@end
//两次提示的默认间隔
static const CGFloat kDefaultPlaySoundInterval = 3.0;
static NSString *kMessageType = @"MessageType";
static NSString *kConversationChatter = @"ConversationChatter";
static NSString *kGroupName = @"GroupName";

@implementation SZLTabBarViewController

+ (void)initialize
{
//    UITabBar *bar = [UITabBar appearance];
//    bar.backgroundImage = [UIImage imageNamed:@"tabbarBack"];
    UITabBarItem *item = [UITabBarItem appearance];
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = [UIColor colorWithHexString:@"#7f8699"];
    attrs[NSFontAttributeName] = [UIFont systemFontOfSize:11];
    [item setTitleTextAttributes:attrs forState:UIControlStateNormal];
    
    NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
    selectedAttrs[NSForegroundColorAttributeName] = DefaultBlueColor;
    selectedAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:11];
    [item setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpChildViewControllers];
    
//    GGTabBar *tabBar = [[GGTabBar alloc] init];
//    tabBar.coverDelegate = self;
//    [self setValue:tabBar forKey:@"tabBar"];
//    if ([SZLAccountHelper isAlreadyLogin]) {
//        [self setupUnreadMessageCount];
//    }
}

- (void)setUpChildViewControllers
{
    ConNewHomeVc *homeVc = [[ConNewHomeVc alloc]init];
    [self addChildVC:homeVc andTitle:@"首页" andImage:@"首页_normal" andSelectImage:@"首页_select"];
    
    ConVipViewController *vipVc = [[ConVipViewController alloc]init];
    [self addChildVC:vipVc andTitle:@"推荐" andImage:@"推荐_normal" andSelectImage:@"推荐_select"];
    
    ConYueVc *yueVc = [[ConYueVc alloc]init];
    [self addChildVC:yueVc andTitle:@"约么" andImage:@"约么_normal" andSelectImage:@"约么_select"];
    
    ConShoppingMallsController *historyVc = [[ConShoppingMallsController alloc]init];
    [self addChildVC:historyVc andTitle:@"商城" andImage:@"商城_normal" andSelectImage:@"商城_select"];
    
    NewPersonalVc *personVc = [[NewPersonalVc alloc]init];
    [self addChildVC:personVc andTitle:@"我的" andImage:@"我的_normal" andSelectImage:@"我的_select"];
}

- (void)addChildVC:(UIViewController *)childVc andTitle:(NSString *)title andImage:(NSString *)image
    andSelectImage:(NSString *)selectedImage
{
    childVc.title = title;
    childVc.tabBarItem.image = [[UIImage imageNamed:image]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    childVc.tabBarItem.selectedImage = [[UIImage imageNamed:selectedImage]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    ConNavigationontroller *nav = [[ConNavigationontroller alloc]initWithRootViewController:childVc];
    [self addChildViewController:nav];
}

- (void)getShareContent
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    [WaterRippleWait waterRippleShowBackgroundColor:[UIColor clearColor]];
    [PersonNetWork getShareContentWithParame:parame response:^(BOOL success, NSString *msg, ShareContentModel *model) {
        [WaterRippleWait hideWaterRipple];
        if (success) {
            [ShareTool share:model];
        }else {
            [MBProgressHUD showError:msg];
        }
    }];
}
//检查相机可用以及权限
- (void)getDeviceIsAvaliable
{
    __WEAK
    UINavigationController *navi = self.childViewControllers[self.selectedIndex];
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device) {
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (status == AVAuthorizationStatusNotDetermined) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        ConQrCodeScannerController *codeVc = [[ConQrCodeScannerController alloc]init];
                        [navi pushViewController:codeVc animated:YES];
                    });
                    NSLog(@"用户第一次同意了访问相机权限");
                } else {
                    NSLog(@"用户第一次拒绝了访问相机权限");
                }
            }];
        } else if (status == AVAuthorizationStatusAuthorized) { // 用户允许当前应用访问相机
            ConQrCodeScannerController *codeVc = [[ConQrCodeScannerController alloc]init];
            [navi pushViewController:codeVc animated:YES];
        } else if (status == AVAuthorizationStatusDenied) { // 用户拒绝当前应用访问相机
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"⚠️ 警告" message:@"请去-> [设置 - 隐私 - 相机 - 玩转地球] 打开访问开关" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertC addAction:alertA];
            [self presentViewController:alertC animated:YES completion:nil];
            
        } else if (status == AVAuthorizationStatusRestricted) {
            NSLog(@"因为系统原因, 无法访问相册");
        }
    } else {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"未检测到您的摄像头" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertC addAction:alertA];
        [self presentViewController:alertC animated:YES completion:nil];
    }
}

- (void)AddCoverViewClick:(AddCoverType)type
{
    if (type == 0) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self getShareContent];
        });
    }else if (type == 1){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self getDeviceIsAvaliable];
        });
    }else if (type == 2) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self getNearAdder];
        });
    }else {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            UINavigationController *navi = self.childViewControllers[self.selectedIndex];
            ConActivityDetailController *detailVc = [[ConActivityDetailController alloc]init];
            detailVc.type = type-1;
            [navi pushViewController:detailVc animated:YES];
        });
    }
}
- (void)getNearAdder
{
    UINavigationController *navi = self.childViewControllers[self.selectedIndex];
    HomeNearAdderViewController *nearVc = [[HomeNearAdderViewController alloc]init];
    [navi pushViewController:nearVc animated:YES];
}


//badgeValue暂未启用
- (void)buyCarAdd
{
    UITabBarItem *buyCarItem = self.tabBar.items[2];
    NSInteger count = [buyCarItem.badgeValue integerValue]+1;
    [[NSUserDefaults standardUserDefaults]setObject:@(count) forKey:BuyCarGoodsCount];
    //buyCarItem.badgeValue = [NSString stringWithFormat:@"%zd",count];
}
// 统计未读消息数
-(void)setupUnreadMessageCount
{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    UITabBarItem *buyCarItem = self.tabBar.items[3];
//    if (unreadCount > 0) {
//        buyCarItem.badgeValue = [NSString stringWithFormat:@"%i",(int)unreadCount];
//    }else{
//        buyCarItem.badgeValue = nil;
//    }
    
//    UIApplication *application = [UIApplication sharedApplication];
//    [application setApplicationIconBadgeNumber:unreadCount];
//    [application setApplicationIconBadgeNumber:0];
    [[NSNotificationCenter defaultCenter]postNotificationName:KPersongbadgeUpdate object:nil];
}
- (void)clearIconUnread
{
    UIApplication *application = [UIApplication sharedApplication];
    [application setApplicationIconBadgeNumber:0];
}
//播放铃声
- (void)playSoundAndVibration
{
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        //如果距离上次响铃和震动时间太短, 则跳过响铃
        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
        return;
    }
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    
    // 收到消息时，播放音频
    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
    // 收到消息时，震动
    [[EMCDDeviceManager sharedInstance] playVibration];
}
- (void)showNotificationWithMessage:(EMMessage *)message
{
    EMPushOptions *options = [[EMClient sharedClient] pushOptions];
    //发送本地推送
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate date]; //触发通知的时间
    
    if (options.displayStyle == EMPushDisplayStyleMessageSummary) {
        EMMessageBody *messageBody = message.body;
        NSString *messageStr = nil;
        switch (messageBody.type) {
            case EMMessageBodyTypeText:
            {
                messageStr = ((EMTextMessageBody *)messageBody).text;
            }
                break;
            case EMMessageBodyTypeImage:
            {
                messageStr = NSLocalizedString(@"message.image", @"Image");
            }
                break;
            case EMMessageBodyTypeLocation:
            {
                messageStr = NSLocalizedString(@"message.location", @"Location");
            }
                break;
            case EMMessageBodyTypeVoice:
            {
                messageStr = NSLocalizedString(@"message.voice", @"Voice");
            }
                break;
            case EMMessageBodyTypeVideo:{
                messageStr = NSLocalizedString(@"message.video", @"Video");
            }
                break;
            default:
                break;
        }
        
        do {
            NSString *title = [[UserProfileManager sharedInstance] getNickNameWithUsername:message.from];
            if (message.chatType == EMChatTypeGroupChat) {
                NSDictionary *ext = message.ext;
                if (ext && ext[kGroupMessageAtList]) {
                    id target = ext[kGroupMessageAtList];
                    if ([target isKindOfClass:[NSString class]]) {
                        if ([kGroupMessageAtAll compare:target options:NSCaseInsensitiveSearch] == NSOrderedSame) {
                            notification.alertBody = [NSString stringWithFormat:@"%@%@", title, NSLocalizedString(@"group.atPushTitle", @" @ me in the group")];
                            break;
                        }
                    }
                    else if ([target isKindOfClass:[NSArray class]]) {
                        NSArray *atTargets = (NSArray*)target;
                        if ([atTargets containsObject:[EMClient sharedClient].currentUsername]) {
                            notification.alertBody = [NSString stringWithFormat:@"%@%@", title, NSLocalizedString(@"group.atPushTitle", @" @ me in the group")];
                            break;
                        }
                    }
                }
                NSArray *groupArray = [[EMClient sharedClient].groupManager getJoinedGroups];
                for (EMGroup *group in groupArray) {
                    if ([group.groupId isEqualToString:message.conversationId]) {
                        title = [NSString stringWithFormat:@"%@(%@)", message.from, group.subject];
                        break;
                    }
                }
            }
            else if (message.chatType == EMChatTypeChatRoom)
            {
                NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
                NSString *key = [NSString stringWithFormat:@"OnceJoinedChatrooms_%@", [[EMClient sharedClient] currentUsername]];
                NSMutableDictionary *chatrooms = [NSMutableDictionary dictionaryWithDictionary:[ud objectForKey:key]];
                NSString *chatroomName = [chatrooms objectForKey:message.conversationId];
                if (chatroomName)
                {
                    title = [NSString stringWithFormat:@"%@(%@)", message.from, chatroomName];
                }
            }
            
            notification.alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
        } while (0);
    }
    else{
        notification.alertBody = NSLocalizedString(@"receiveMessage", @"you have a new message");
    }
    
#warning 去掉注释会显示[本地]开头, 方便在开发中区分是否为本地推送
    //notification.alertBody = [[NSString alloc] initWithFormat:@"[本地]%@", notification.alertBody];
    
    notification.alertAction = NSLocalizedString(@"open", @"Open");
    notification.timeZone = [NSTimeZone defaultTimeZone];
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
    } else {
        notification.soundName = UILocalNotificationDefaultSoundName;
        self.lastPlaySoundDate = [NSDate date];
    }
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    [userInfo setObject:[NSNumber numberWithInt:message.chatType] forKey:kMessageType];
    [userInfo setObject:message.conversationId forKey:kConversationChatter];
    notification.userInfo = userInfo;
    
    //发送通知
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    UIApplication *application = [UIApplication sharedApplication];
    application.applicationIconBadgeNumber += 1;
}



@end
